<?php
class ApiBaseClass {

    private static $instance = null ;

    public $_request;

    public $_response;

    public $_context;

    public $_data;

    public $form;

    public $employeeService = null ;

    private $authenticationService = null ;

    private $authenticated = false ;
    /**
     * @param sfForm $form
     * @return
     */
    public function setForm(sfForm $form) {
        if (is_null($this -> form)) {
            $this -> form = $form;
        }
    }

    public function _init() {
        $this -> _request = sfContext::getInstance() -> getRequest();
        $this -> _response = sfContext::getInstance() -> getResponse();
        $this -> _data = array('errors' => 0, 'message' => '', 'response' => '');
        $this -> _context = sfContext::getInstance();

        $this->authenticationService = new APIAuthenticationService() ;
        $this->authenticated = $this->authenticationService->authenticate() ;
        APIUserRoleManagerFactory::setAuthenticationService($this->authenticationService);

    }

    public function execute() {
        $action = $this -> _request -> getParameter('actions') . "Action";
        $this -> _init();
        if (method_exists($this, $action)&& $this->authenticated == true ) {
            call_user_func(array($this, $action));
        } else {
            $this -> _data['errors'] = 0;
            $this -> _data['message'] = "Method does not exist";
        }

        $this -> _response -> setContent(json_encode($this -> _data));
        // remove all login
        $this->authenticationService->clearCredentials() ;
    }



    protected function IsActionAccessible($empNumber) {

        $isValidUser = true;

        $loggedInEmpNum = $this -> _context -> getUser() -> getEmployeeNumber();

        $userRoleManager = $this -> _context -> getUserRoleManager();
        $accessible = $userRoleManager -> isEntityAccessible('Employee', $empNumber);

        if ($empNumber != $loggedInEmpNum && (!$accessible)) {
            $isValidUser = false;
        }

        return $isValidUser;
    }


    /**
     * Get EmployeeService
     * @returns EmployeeService
     */
    public function getEmployeeService() {
        if(is_null($this->employeeService)) {
            $this->employeeService = new EmployeeService();
            $this->employeeService->setEmployeeDao(new EmployeeDao());
        }
        return $this->employeeService;
    }

    public static function getInstance () {
        if (!isset(self::$instance)) {
            self::$instance = new ApiBaseClass() ;
        }
        return self::$instance ;
    }


}
?>